package com.yyh.fanshe;

import java.lang.reflect.Constructor;

public class Demo7 {
    public static void main(String[] args) throws Exception {
        //1.获取User.java类文件
        Class aClass = Class.forName("com.yyh.fanshe.User");
        //2.获取构造方法对象
        Constructor constructor = aClass.getDeclaredConstructor(String.class, int.class, String.class, String.class);
        System.out.println("constructor = " + constructor);
        // constructor = public com.yyh.fanshe.User(java.lang.String,int,java.lang.String,java.lang.String)
        System.out.println("------------------------------------------------");
        //3.获取该构造方法的权限修饰符的魔法值
        int modifiers = constructor.getModifiers();
        System.out.println("modifiers = " + modifiers);//modifiers = 1
        System.out.println("------------------------------------------------");
        //4.获取该构造方法的名称
        String name = constructor.getName();
        System.out.println("name = " + name);//name = com.yyh.fanshe.User
        System.out.println("------------------------------------------------");
        //5.获取该构造方法的形式参数的个数
        int parameterCount = constructor.getParameterCount();
        System.out.println("parameterCount = " + parameterCount);//parameterCount = 4
        System.out.println("------------------------------------------------");
        //6.获取该构造方法的形参的类型并按照顺序存入数组
        Class[] parameterTypes = constructor.getParameterTypes();
        for (Class parameterType : parameterTypes) {
            System.out.println("parameterType = " + parameterType);
            /*parameterType = class java.lang.String
            parameterType = int
            parameterType = class java.lang.String
            parameterType = class java.lang.String*/
        }
        System.out.println("------------------------------------------------");
        //7.执行该构造方法对象并创建实例化对象
        //打开暴力访问开关
        constructor.setAccessible(true);
        User user = (User) constructor.newInstance("张三", 18, "男", "上海");
        System.out.println("user = " + user);//user = User{name='张三', age=18, sex='男', address='上海'}
    }
}
